package com.qf.first.realm;

import com.qf.first.base.pojo.vo.UserVo;
import com.qf.first.entity.User;
import com.qf.first.mapper.UserMapper;
import lombok.SneakyThrows;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.BeanUtils;

import javax.annotation.Resource;
import javax.security.auth.login.AccountLockedException;

public class UserRealm extends AuthorizingRealm {
    @Resource
    UserMapper userMapper;

    /**
     * 权限功能
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        return null;
    }

    /**
     * 登录认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @SneakyThrows
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        /*
         * Object principal,从数据库获取的对象
         * Object hashedCredentials,从数据库获取的密码（加密）
         * ByteSource credentialsSalt,加密语言，额外的加密字段（非必要）
         * String realmName，用户输入的用户名*/

        //第一步，从token中获取用户名
        String username = (String) authenticationToken.getPrincipal();
        System.out.println(username);
        //第二部，根据用户名从数据库获取用户对象
        User user = userMapper.selectUserByName(username);
        //第三部，判断用户
        if (user == null) {
            throw new AccountException("账号密码错误");
        }
        if (!user.getStatus()) {
            throw new AccountLockedException("账号已注销或被禁用");
        }
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user, userVo);
        //实例化SimpleAuthenticationInfo
        SimpleAuthenticationInfo simpleAuthenticationInfo =
                new SimpleAuthenticationInfo(username, user.getPassword(), getName());
        return simpleAuthenticationInfo;
    }
}
